package com.yuan.yblog.portal.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuan.yblog.common.service.EntityCacheService;
import com.yuan.yblog.crud.entity.User;
import com.yuan.yblog.crud.entity.UserMessage;
import com.yuan.yblog.crud.service.IUserMessageService;
import com.yuan.yblog.crud.service.IUserMessageTypeService;
import com.yuan.yblog.crud.service.IUserService;
import com.yuan.yblog.portal.dao.mapper.UserMessageDao;
import com.yuan.yblog.portal.pojo.VO.UserMessageVO;
import com.yuan.yblog.portal.pojo.contants.UserMessageStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hepeiyuan
 * @description 用户消息服务类
 * @createDate 2023-12-03 14:18:01
 */
@Service
public class UserMessageService {
    @Autowired
    UserMessageDao userMessageDao;

    @Autowired
    IUserMessageService iUserMessageService;

    @Autowired
    IUserService iUserService;

    @Autowired
    IUserMessageTypeService iUserMessageTypeService;

    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    EntityCacheService entityCacheService;

    /**
     * 分页查询当前用户收到的消息
     */
    public IPage<UserMessageVO> list(Boolean isRead, Long pageNumber, Long pageSize, String sortKey, Boolean isDesc) {
        User receiver = authenticationService.getLoginUser();

        List<UserMessage> userMessageList = userMessageDao.listByReceiverId(receiver.getId(), isRead, (pageNumber-1)*pageSize, pageSize, sortKey, isDesc);
        Long total = userMessageDao.listByReceiverIdCount(receiver.getId(), isRead);

        // 查询发送者姓名和消息类型
        List<UserMessageVO> records = new ArrayList<>();
        for (UserMessage userMessage : userMessageList) {
            String fromUserName = iUserService.selectByIdAndBuildCache(userMessage.getFromUserId()).getUsername();
            String userMessageTypeKey = iUserMessageTypeService.selectByIdAndBuildCache(userMessage.getMessageType()).getTypeKey();
            UserMessageVO vo = UserMessageVO.getUserMessageVO(userMessage);
            vo.setFromUserName(fromUserName);
            vo.setUserMessageKey(userMessageTypeKey);
            vo.setToUserName(receiver.getUsername());
            records.add(vo);
        }
        // 返回结果
        IPage<UserMessageVO> results = new Page<>(pageNumber,pageSize,total);
        results.setRecords(records);
        return results;
    }

    /**
     * 用户阅读消息
     */
    public int ReadMessage(List<Long> messageIds) {
        // 生效数目
        int count = 0;
        User user = authenticationService.getLoginUser();
        if(messageIds==null || messageIds.isEmpty()) {
            return count;
        }
        List<UserMessage> ums = iUserMessageService.getBaseMapper().selectBatchIds(messageIds);
        for (UserMessage um : ums) {
            // 判断是否是该登录者的消息
            if(!um.getToUserId().equals(user.getId())){
                continue;
            }
            um.setStatus(UserMessageStatus.read);
            boolean succeed = iUserMessageService.updateAndDeleteCache(um);
            if (succeed) {
                count++;
            }
        }
        return count;
    }

    /**
     * 用户删除消息
     */
    public int deleteByIds(List<Long> messageIds) {
        // 生效数目
        int count = 0;
        User user = authenticationService.getLoginUser();
        if(messageIds==null || messageIds.isEmpty()) {
            return count;
        }
        List<UserMessage> ums = iUserMessageService.getBaseMapper().selectBatchIds(messageIds);
        for (UserMessage um : ums) {
            // 判断是否是该登录者的消息
            if(!um.getToUserId().equals(user.getId())){
                continue;
            }
            um.setStatus(UserMessageStatus.invalid);
            boolean succeed = iUserMessageService.updateAndDeleteCache(um);
            if (succeed) {
                count++;
            }
        }
        return count;
    }

    /**
     * 新增消息
     */
    public int insert(UserMessageVO userMessageVO){
        iUserMessageService.insert(userMessageVO.toInsertEntity());
        return 0;
    }

    /**
     * 获取未读消息数目
     */
    public Long getUnreadCount() {
        User currentUser = authenticationService.getLoginUser();
        return iUserMessageService.count(new QueryWrapper<UserMessage>()
                .eq("to_user_id",currentUser.getId())
                .eq("status",UserMessageStatus.unread));
    }

}




